package com.starblink.store.memanage.ui

import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.bus.bean.RemoveStoresEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.common.view.store.StoreRecommendResultCell
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.store.databinding.ActivityNewManageStoreBinding
import com.starblink.store.databinding.ItemMemanageStoreBinding
import com.starblink.store.databinding.ItemMineManageEmptyBinding
import com.starblink.store.databinding.ItemMineManageTitleBinding
import com.starblink.store.memanage.adapter.ManageStoreEmptyCell
import com.starblink.store.memanage.adapter.ManageTitleCell
import com.starblink.store.memanage.adapter.SubStoresCell
import com.starblink.store.memanage.vm.ManageStoreVM

@Route(path = RoutePage.Store.PAGE_MY_MANAGE)
class NewManageStoreActivity : BaseTVMActivity<ActivityNewManageStoreBinding, ManageStoreVM>() {

    @Autowired(name = RoutePage.Store.FOLLOWED)
    @JvmField
    var hasFollowedStore: Boolean = false //是否有订阅

    override fun initViewBinding(): ActivityNewManageStoreBinding =
        ActivityNewManageStoreBinding.inflate(layoutInflater)

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.list.value!!).apply {
            addVhDelegate {
                SubStoresCell(
                    ItemMemanageStoreBinding.inflate(it.inflater, it, false),
                    { position, merchantWebVOF ->
                        CommonRoute.startStoreDetail(mActivity, merchantWebVOF.id)
                        if (merchantWebVOF.read == false) {
                            viewModel.readMessage(position, merchantWebVOF)
                            ApolloValSetExt.setApolloVal<MerchantWebVOF>(
                                merchantWebVOF, "read",
                                true
                            )
                            adapter.notifyDataSetChanged()
                        }
                    }, { position, merchantWebVOF ->
                        viewModel.removeItem(position)
                    })
            }
            addVhDelegate {
                StoreRecommendResultCell(
                    pageDef = SpmPageDef.MeStoresSubListPage,
                    viewGroup = it,
                ) { merchant, position ->
                    CommonMutateManage.subscribeOrNotMerchant(
                        this@NewManageStoreActivity,
                        merchant.id,
                        merchant.merchantName,
                        merchant.subOrNot,
                        resultCallback = {
                            if (it) {
                                ApolloValSetExt.setApolloVal<MerchantWebVOF>(
                                    merchant, "subOrNot",
                                    !merchant.subOrNot
                                )
                                refreshItem(position)
                            }
                        }, merchant = merchant
                    )
//                    SpmTrackHandler.addSingleTrackData(
//                        SkAntEntity(
//                            event = TrackEvent.elementClick.value,
//                            spmCnt = GTrackerAssistUtils.fetchElementValue(
//                                SpmPageDef.MeStoresSubListPage,
//                                SpmElementDef.StoreSub
//                            ),
//                            params = mapOf(
//                                "merchantName" to (merchant.merchantName ?: ""),
//                                "index" to position.toString(),
//                                "result" to "1"
//                            )
//                        )
//                    )
                }
            }
            addVhDelegate {
                //my service标题
                ManageTitleCell(
                    ItemMineManageTitleBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                ManageStoreEmptyCell(
                    ItemMineManageEmptyBinding.inflate(it.inflater, it, false)
                )
            }
        }
    }

    private fun refreshItem(position: Int) {
        adapter.notifyItemChanged(position)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewBinding.searchTip.text = "Search store"
        setStatusBarBlackText()
        if (hasFollowedStore) {
            viewModel.fetchMySubscribeMerchantWeb(true, false)
        } else {
            viewModel.addEmptyView()
        }

        viewModel.list.observe(this) {
            if (viewBinding.recyclerView.adapter == null) {
                viewBinding.recyclerView.adapter = adapter//单位px
            } else {
                adapter.notifyDataSetChanged()
            }
        }


        flowData()
    }

    override fun initView() {
        super.initView()
        viewBinding.recyclerView.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerView.setHasFixedSize(true)
        viewBinding.recyclerView.itemAnimator = null

//        viewBinding.recyclerView.addItemDecoration(DefaultDecoration(this).apply {
//            startVisible = true
//            endVisible = true
//            this.setDivider(12.dp2px())
//        })

        viewBinding.refresher.setEnableLoadMore(true)
        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setOnLoadMoreListener {
            if (viewModel.loadedRecommend) {
                viewModel.loadRecommendStores()
            } else {
                viewModel.fetchMySubscribeMerchantWeb(false, false)
            }
            viewBinding.refresher.finishLoadMore(5000)
        }

        viewBinding.title.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }

            override fun onRightClick(titleBar: TitleBar?) {
                navigationTo(RoutePage.Store.PAGE_MANAGE) {}
            }
        })
        FontUtil.setMontseratSemiBold(viewBinding.title.titleView)

        viewBinding.llSearch.setOnClickListener {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                withInt(RoutePage.Search.ARG_SCENE, RoutePage.Search.SCENE.STORES.value)
            }
        }
    }


    /**
     * 同步订阅数据
     */
    private fun flowData() {
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) {
            if (it.id != null) {
                if (it.followed) {
                    if (it.merchant != null) {
                        viewModel.addSubscribeStore(it.merchant!!)
                    } else {
                        viewModel.fetchMySubscribeMerchantWeb(
                            showLoading = false,
                            initRefresh = true
                        )
                    }
                } else {
                    for ((index, post) in viewModel.list.value!!.withIndex()) {
                        if (post != null && post is MerchantWebVOF && it.id == post.id) {
                            viewModel.removeItem(index)
                            break
                        }
                    }
                }
            }
        }

        //同步取消店铺
        FlowBus.with<RemoveStoresEvent>(FlowConst.REMOVE_STORE_EVENT).register(this) {
            if (it.ids != null) {
                var removed = false

                for (id in it.ids!!) {
                    val first = viewModel.list.value!!.indexOfFirst {
                        it is MerchantWebVOF && it.id == id
                    }
                    viewModel.list.value!!.removeAt(first)
                    removed = true

                    refreshRecommendListSub(id, false)
                }
                if (viewModel.list.value?.isEmpty() == true) {
                    viewModel.list.value?.add(0)
                }
                if (removed) {
                    viewModel.list.value = viewModel.list.value
                }
                Log.e("ManageStoreVM", "====${viewModel.list.value}")
            }
        }

        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.fetchMySubscribeMerchantWeb(showLoading = false, initRefresh = true)
        }
    }

    private fun refreshRecommendListSub(id: String, sub: Boolean) {
        //刷新推荐列表订阅状态
        val index = viewModel.list.value!!.indexOfFirst { it is MerchantWebVOF && it.id == id }
        if (index >= 0) {
            val merchant = viewModel.list.value!![index]
            if (merchant is MerchantWebVOF && merchant.subOrNot != sub) {
                ApolloValSetExt.setApolloVal<MerchantWebVOF>(merchant, "subOrNot", sub)
                viewModel.list.value!![index] = merchant
            }
            viewModel.list.value = viewModel.list.value
        }
    }

    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.MeStoresSubListPage)
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(SpmPageDef.MeStoresSubListPage)
    }
}